How to handle asynchronous operations in Node.js? Provide an example.
How to handle asynchronous operations in Node.js? Provide an example.
304
27-Sep-2023
Updated on 28-Sep-2023
Aryan Kumar
28-Sep-2023Handling asynchronous operations in Node.js is fundamental because Node.js is designed to be non-blocking and asynchronous, making it efficient for handling I/O-bound tasks. There are several ways to work with asynchronous operations in Node.js, including callbacks, Promises, and the async/await syntax. Here's an example using callbacks, which is the traditional way of handling asynchronous operations in Node.js:
Example: Handling Asynchronous Operations with Callbacks
Suppose you have a function that reads a file asynchronously and performs an operation on its contents. Here's how you would handle it with callbacks:
In this example:
We define a function readFileAsync that reads a file asynchronously using the fs.readFile function. It takes a filePath and a callback as parameters.
Inside the readFileAsync function, we handle errors and process the file data asynchronously.
The callback function is called with two arguments: err for the error (if any) and data for the processed data.
In the usage section, we call readFileAsync, passing the file path and a callback function to handle the result.
Inside the callback function, we check for errors and log the processed data or handle errors as needed.
While callbacks are a common way to handle asynchronous operations in Node.js, they can lead to callback hell (also known as the "Pyramid of Doom") when dealing with complex nested asynchronous code. To mitigate this, Node.js introduced Promises and the async/await syntax, which provide more structured and readable ways to work with asynchronous code.